<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\captcha\Captcha;
use think\facade\Session;
use think\facade\Config;
use think\Db;
use \think\facade\Lang;

class Youdao extends controller
{
    public function do_call($url, $method, $header, $param, $expectContentType, $timeout = 3000)
	{
	    $curl = curl_init();
	    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	    if (!empty($header)) {
	        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
	    }
	    $data = http_build_query($param);
	    if ($method == 'post') {
	        curl_setopt($curl, CURLOPT_POST, 1);
	        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	    } else if ($method == 'get') {
	        $url = $url . '?' . $data;
	    } else {
	        print 'http method not support';
	        return null;
	    }
	    curl_setopt($curl, CURLOPT_URL, $url);
	    $r = curl_exec($curl);
	    $contentType = curl_getinfo($curl, CURLINFO_CONTENT_TYPE);
	    if (strpos($contentType, $expectContentType) === false) {
	        echo $r;
	        $r = null;
	    }
	    curl_close($curl);
	    return $r;
	}

	public function add_auth_params($param, $appKey, $appSecret)
	{
	    if (array_key_exists('q', $param)) {
	        $q = $param['q'];
	    } else {
	        $q = $param['img'];
	    }
	    $salt = $this->create_uuid();
	    $curtime = strtotime("now");
	    $sign = $this->calculate_sign($appKey, $appSecret, $q, $salt, $curtime);
	    $param['appKey'] = $appKey;
	    $param['salt'] = $salt;
	    $param["curtime"] = $curtime;
	    $param['signType'] = 'v3';
	    $param['sign'] = $sign;
	    return $param;
	}

	public function create_uuid()
	{
	    $str = md5(uniqid(mt_rand(), true));
	    $uuid = substr($str, 0, 8) . '-';
	    $uuid .= substr($str, 8, 4) . '-';
	    $uuid .= substr($str, 12, 4) . '-';
	    $uuid .= substr($str, 16, 4) . '-';
	    $uuid .= substr($str, 20, 12);
	    return $uuid;
	}

	public function calculate_sign($appKey, $appSecret, $q, $salt, $curtime)
	{
	    $strSrc = $appKey . $this->get_input($q) . $salt . $curtime . $appSecret;
	    return hash("sha256", $strSrc);
	}

	public function get_input($q)
	{
	    if (empty($q)) {
	        return null;
	    }
	    $len = mb_strlen($q, 'utf-8');
	    return $len <= 20 ? $q : (mb_substr($q, 0, 10) . $len . mb_substr($q, $len - 10, $len));
	}


	public function create_request($zhi)
	{
		$APP_KEY='2d924e8c4c015df8';
		$APP_SECRET='JEqBDdZFgOjDvtbmnJWjDpCeQUuaK2On';
	    
	    $q = $zhi;
	    $from = "en";
	    $to = "zh-CHS";

	    $params = array('q' => $q,
	        'from' => $from,
	        'to' => $to);
	    $params = $this->add_auth_params($params, $APP_KEY, $APP_SECRET);
	    $r = $this->do_call('https://openapi.youdao.com/api', 'post', array(), $params, 'application/json');
	    $data=json_decode($r,true);
	    if(isset($data['translation'])){
	    	return $data['translation'][0];
	    }else{
	    	return '';
	    }
	}

	/*翻译detail key*/
	public function detail_check_lang_key(){
        $filename='result.txt';
        $load=explode('application', __DIR__);
        if(file_exists($load[0].'application/lang/'.$filename)){
            unlink($load[0].'application/lang/'.$filename);
        }

        $sql="SELECT `key`,id FROM lily_products_detail GROUP BY `key`";
        $data=Db::query($sql);
        /*
        规则：字母个数小于等于3个 不翻译
        排除数组 $pai中的
        */
        $pai=array('D1 max','DM max','nRef','S x l','d1xd2xh','VDWL','Rsmin','Lily Number','CETC1','CETC2','F Min','Y Max','PN Number5','PN Number6','PN Number7','PN Number8','B00308','B00234','B04144','0029176416033','0029176086533','da min','Da max','ras max','e - ISO Factor3','Y0 - ISO Factor4','Y1 - ISO Factor5','Y2 - ISO Factor6','PN Number2','PN Number3','PN Number4','ECCN','DFARS','dimg');
        $i=1;
        foreach ($data as $key => $value) {
            $zhi=trim($value['key']);

            $len=strlen($zhi);
            if($len>3 && !in_array($zhi, $pai)){
                if(lang::has($zhi)==false){
                    /*echo $value['id']." ".$i."---".$zhi."</br>";
                    $i++;*/
                    $strtxt="'".$zhi."'=>'".$this->create_request($zhi)."',\n";
                   
                    $myfiletxt=fopen($load[0].'application/lang/'.$filename, "a+");
                    fwrite($myfiletxt, $strtxt);
                    fclose($myfiletxt);
                }
            }
        }
    }

    public function detail_check_lang_value(){
    	$filename='result_value.txt';
        $load=explode('application', __DIR__);
        if(file_exists($load[0].'application/lang/'.$filename)){
            unlink($load[0].'application/lang/'.$filename);
        }
    	$sql="SELECT `value` FROM lily_products_detail WHERE `value` !='' AND  `value` NOT LIKE '%lb' AND `value` NOT LIKE '%mm' AND `value` NOT LIKE '%N' AND `value` NOT LIKE '%1/min' AND `value` NOT LIKE '%Nm' AND `value` NOT LIKE '%kg' AND `value` NOT LIKE '%N/µm' AND `value` NOT LIKE '%Nm/mrad' AND `value` NOT LIKE '%cm^2' AND  `value` NOT LIKE '%°' AND `value` not regexp '[0-9]+' AND  LENGTH(`value`)>3 AND `value` !='—\"' AND `value`!='NSK 'GROUP BY `value`";
    	$data=Db::query($sql);
    	foreach ($data as $key => $value) {
            $zhi=trim($value['value']);
            $len=strlen($zhi);
            
            if(lang::has($zhi)==false){
            	/*echo $i."---".$zhi."</br>";
                    $i++;*/
                $strtxt="'".$zhi."'=>'".$this->create_request($zhi)."',\n";
                $myfiletxt=fopen($load[0].'application/lang/'.$filename, "a+");
                fwrite($myfiletxt, $strtxt);
                fclose($myfiletxt);
            }
            
        }
    }

    public function update_class_name(){
    	$sql="SELECT id,cname FROM lily_classifys where alias_name=''";
    	$data=Db::query($sql);
    	foreach ($data as $key => $value) {
    		$sql2="update lily_classifys set alias_name='".$this->create_request($value['cname'])."' where id=".$value['id'];
    		Db::query($sql2);
    	}
    }
    

}